package com.ruibang.glass.produce.service.impl;

import com.alibaba.excel.EasyExcel;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ruibang.glass.common.constants.RedisKey;
import com.ruibang.glass.produce.constant.Constants;
import com.ruibang.glass.produce.domain.req.CommonTrendChartReq;
import com.ruibang.glass.produce.domain.req.ReportOhDetectDetailReq;
import com.ruibang.glass.produce.domain.resp.ReportOhDetectDetailTrendChart;
import com.ruibang.glass.produce.entity.ReportOhDetectDetail;
import com.ruibang.glass.produce.mapper.ReportOhDetectDetailMapper;
import com.ruibang.glass.produce.service.ReportOhDetectDetailService;
import com.ruibang.glass.produce.util.ExcelStyleUtils;
//import com.teaming.cloud.framework2.autoconfigure.redis.RedisSingleService;
import com.teaming.cloud.framework2.autoconfigure.redis.RedisSingleService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.time.LocalDateTime;
import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 * 生产-理化-β-OH值 服务实现类
 * </p>
 *
 * @author songJinKang
 * @since 2024-03-12
 */
@Slf4j
@Service
public class ReportOhDetectDetailServiceImpl extends ServiceImpl<ReportOhDetectDetailMapper, ReportOhDetectDetail> implements ReportOhDetectDetailService {

    @Autowired
    private RedisSingleService redisService;
//    @PostConstruct
//    public void initData() {
//        List<ReportOhDetectDetail> list = this.list();
//        for (ReportOhDetectDetail moistureDeteciton : list) {
//            String auditById = moistureDeteciton.getAuditById();
//            if (StringUtils.isNotBlank(auditById)) {
//                Object auditObj = redisService.hget(RedisKey.USER_GROUP_TYPE, auditById);
//                if (auditObj != null) {
//                    moistureDeteciton.setAuditBy(auditObj.toString());
//                }
//            }
//            String checkById = moistureDeteciton.getCheckById();
//            if (StringUtils.isNotBlank(checkById)) {
//                Object checkObj = redisService.hget(RedisKey.USER_GROUP_TYPE, checkById);
//                if (checkObj != null) {
//                    moistureDeteciton.setCheckBy(checkObj.toString());
//                }
//            }
//        }
//        updateBatchById(list);
//    }

    @Override
    public IPage<ReportOhDetectDetail> pageQuery(ReportOhDetectDetailReq reportOhDetectDetailReq) {
        QueryWrapper<ReportOhDetectDetail> qw = new QueryWrapper<>();
        qw.lambda().eq(ReportOhDetectDetail::getIsDelete, Constants.ZERO_STR);
        qw.lambda().like(StringUtils.isNotBlank(reportOhDetectDetailReq.getSampleCode()), ReportOhDetectDetail::getSampleCode, reportOhDetectDetailReq.getSampleCode());
        if (reportOhDetectDetailReq.getSampleStartTime() != null && reportOhDetectDetailReq.getSampleEndTime() != null) {
            qw.lambda().ge(ReportOhDetectDetail::getSampleTime, reportOhDetectDetailReq.getSampleStartTime());
            qw.lambda().le(ReportOhDetectDetail::getSampleTime, reportOhDetectDetailReq.getSampleEndTime());
        }
        qw.lambda().orderByDesc(ReportOhDetectDetail::getSampleTime);
        return this.page(new Page<>(reportOhDetectDetailReq.getPageNo(), reportOhDetectDetailReq.getPageSize()), qw.lambda());
    }

    @Override
    public void delete(String id) {
        lambdaUpdate().eq(ReportOhDetectDetail::getId, id).set(ReportOhDetectDetail::getIsDelete, Constants.ONE_STR).update();
    }

    @Override
    public ReportOhDetectDetailTrendChart trendChart(CommonTrendChartReq trendChartReq) {
        //默认查询3天
        if (trendChartReq.getStartTime() == null || trendChartReq.getEndTime() == null) {
            LocalDateTime now = LocalDateTime.now();
            trendChartReq.setStartTime(now.minusDays(3));
            trendChartReq.setEndTime(now);
        }
        //组合数据
        ReportOhDetectDetailTrendChart reportOhDetectDetailTrendChart = new ReportOhDetectDetailTrendChart();
        List<ReportOhDetectDetail> data = baseMapper.trendChart(trendChartReq);
        if (CollectionUtils.isNotEmpty(data)) {
            reportOhDetectDetailTrendChart.setData(data);
            reportOhDetectDetailTrendChart.setCollectTime(data.stream().map(e -> e.getSampleTime().format(Constants.DATE_TIME_FORMATTER)).collect(Collectors.toList()));
            //检测值
            reportOhDetectDetailTrendChart.setAvg(data.stream().map(ReportOhDetectDetail::getAvg).collect(Collectors.toList()));
            reportOhDetectDetailTrendChart.setF1(data.stream().map(ReportOhDetectDetail::getF1).collect(Collectors.toList()));
            reportOhDetectDetailTrendChart.setF2(data.stream().map(ReportOhDetectDetail::getF2).collect(Collectors.toList()));
            reportOhDetectDetailTrendChart.setF3(data.stream().map(ReportOhDetectDetail::getF3).collect(Collectors.toList()));
            reportOhDetectDetailTrendChart.setF4(data.stream().map(ReportOhDetectDetail::getF4).collect(Collectors.toList()));
            reportOhDetectDetailTrendChart.setF5(data.stream().map(ReportOhDetectDetail::getF5).collect(Collectors.toList()));
        }
        return reportOhDetectDetailTrendChart;
    }

    @Override
    public void edit(ReportOhDetectDetail reportOhDetectDetail) {
        setUserName(reportOhDetectDetail);
        this.updateById(reportOhDetectDetail);
    }

    private void setUserName(ReportOhDetectDetail reportOhDetectDetail) {
        String auditById = reportOhDetectDetail.getAuditById();
        String checkById = reportOhDetectDetail.getCheckById();
        if (StringUtils.isNotBlank(auditById)) {
            Object userObj = redisService.hget(RedisKey.USER_GROUP_TYPE, auditById);
            if (userObj != null && StringUtils.isNotBlank(userObj.toString())) {
                reportOhDetectDetail.setAuditBy(userObj.toString());
            }
        } else {
            reportOhDetectDetail.setAuditBy("");
        }
        if (StringUtils.isNotBlank(checkById)) {
            Object userObj = redisService.hget(RedisKey.USER_GROUP_TYPE, checkById);
            if (userObj != null && StringUtils.isNotBlank(userObj.toString())) {
                reportOhDetectDetail.setCheckBy(userObj.toString());
            }
        } else {
            reportOhDetectDetail.setCheckBy("");
        }
    }

    @Override
    public void insert(ReportOhDetectDetail reportOhDetectDetail) {
        reportOhDetectDetail.setIsDelete(Constants.ZERO_STR);
        setUserName(reportOhDetectDetail);
        this.save(reportOhDetectDetail);
    }

    @Override
    public void export(ReportOhDetectDetailReq reportOhDetectDetailReq, HttpServletResponse response) {
        reportOhDetectDetailReq.setPageNo(-1);
        reportOhDetectDetailReq.setPageSize(-1);
        IPage<ReportOhDetectDetail> page = this.pageQuery(reportOhDetectDetailReq);
        if (page != null && CollectionUtils.isNotEmpty(page.getRecords())) {
            List<ReportOhDetectDetail> reportOhDetectDetailList = page.getRecords();
            try {
                EasyExcel.write(response.getOutputStream(), ReportOhDetectDetail.class)
                        .registerWriteHandler(ExcelStyleUtils.createTableStyle())
                        .sheet("history_data").doWrite(reportOhDetectDetailList);
            } catch (IOException e) {
                log.error("数据导出失败：{}", e.getMessage());
            }
        }
    }


    private double getAvg(ReportOhDetectDetail reportOhDetectDetail) {
        int count = 0;
        double sum = 0;
        Double f1 = reportOhDetectDetail.getF1();
        Double f2 = reportOhDetectDetail.getF2();
        Double f3 = reportOhDetectDetail.getF3();
        Double f4 = reportOhDetectDetail.getF4();
        Double f5 = reportOhDetectDetail.getF5();
        if (f1 != null) {
            count++;
            sum += f1;
        }
        if (f2 != null) {
            count++;
            sum += f2;
        }
        if (f3 != null) {
            count++;
            sum += f3;
        }
        if (f4 != null) {
            count++;
            sum += f5;
        }
        if (f5 != null) {
            count++;
            sum += f5;
        }
        return count / sum;
    }
}
